import { ChangeEvent } from 'react'
import useAvatar from '@/hooks/useAvatar'
import { SET_AVATAR } from '@/store/actions'

const AvatarPanel = () => {
  const { getAvatar, lists } = useAvatar()
  const { avatarUrl } = useSelector((state: any) => state.user)
  const searchParams = new URL(avatarUrl).searchParams
  const localParams = pick(fromPairs([...searchParams.entries()]), map(lists, 'key'))
  const dispatch = useDispatch()
  const [params, setParams] = useState({
    ...mapValues(localParams, (v: string, k: string) => {
      return findIndex(find(lists, { key: k })?.list, (val: string) => val === v) + 1
    })
  })

  const handleChange = (item: { key: any; list: any }) => (e: ChangeEvent<HTMLInputElement>) => {
    const { key, list } = item
    const value = e.target.value
    const options = { ...params, [key]: value !== '' ? clamp(value, 1, list.length) : '' }
    setParams(options)
    dispatch({ type: SET_AVATAR, avatarUrl: getAvatar(options) })
  }
  return (
    <Grid container spacing={2} direction="row">
      <Grid xs={8} item container spacing={2} direction="column">
        {lists.map((item) => {
          const { key, list } = item
          return (
            <Grid item key={key}>
              <TextField
                size="small"
                id={key}
                label={`${key} 1-${list.length}`}
                type="number"
                variant="standard"
                value={params[key]}
                InputLabelProps={{
                  shrink: true
                }}
                inputProps={{
                  step: 1
                }}
                onChange={handleChange(item)}
              />
            </Grid>
          )
        })}
      </Grid>
      <Grid item xs={4} container direction="column" justifyContent="space-between" alignItems="center">
        <Avatar sx={{ width: 100, height: 100 }} src={avatarUrl} />
      </Grid>
    </Grid>
  )
}

export default AvatarPanel
